package cn.kfu.config;

import cn.kfu.model.User;
import cn.kfu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 和数据库交互 看看用户信息 权限信息
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 获取权限信息的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 获取认证信息的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // token是封装好的用户提交的用户名和密码
        String username = ((UsernamePasswordToken) token).getUsername();
        // 获取用户
        User user = userService.findUserByUsername(username);
        if (user == null) {
            return null;
        } else {
            // 封装AuthenticationInfo
            ByteSource bsSalt = new SimpleByteSource(user.getSalt());
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), bsSalt, getName());
            return authenticationInfo;
        }

    }
}
